package club.kingyin.easycache.component.annotation.handler;

import club.kingyin.easycache.cache.AbstractCache;
import club.kingyin.easycache.key.AbstractEasyCacheKey;
import club.kingyin.easycache.key.EasyCacheKey;
import club.kingyin.easycache.method.CacheMethod;
import club.kingyin.easycache.proxy.ProxyCacheInvokePostProcess;
import lombok.extern.slf4j.Slf4j;

/**
 * 执行耗时统计模块，仅用于测试缓存性能
 */
@Slf4j
public class TimerWithExecution implements ProxyCacheInvokePostProcess {
    @Override
    public boolean getCacheInterceptor(boolean pre, CacheMethod target, EasyCacheKey key) {
        ((AbstractEasyCacheKey) key).affiliated("before-exec",System.currentTimeMillis());
        return pre;
    }

    @Override
    public void postProcessAfterGetCache(CacheMethod target, AbstractCache cache, Object res, EasyCacheKey key) {
        long after = System.currentTimeMillis();
        ((AbstractEasyCacheKey) key).affiliated("after-exec",after);
        long before = ((long) ((AbstractEasyCacheKey) key).obtain("before-exec"));
        long timeConsuming = after - before;
        if (timeConsuming >= 2000) {
            log.info("模块：[{}] 方法：[{}] 执行耗时-异常：{} ms",key.getModule(),key.getMethodName(),timeConsuming );
        } else {
            log.info("模块：[{}] 方法：[{}] 执行耗时-正常：{} ms",key.getModule(),key.getMethodName(),timeConsuming );
        }
    }
}
